angular.module('BaseControl')

.directive("percentbox", ['BaseEnum', 'BaseClass', 'BaseFunction', function(BaseEnum, BaseClass, BaseFunction) {
    return {
        restrict: "E",	// 指令是一个元素 (并非属性)，备选项有"A"、"E" 和 "C"， "M" ,分别代表attribute、element、class和comment（默认值为"A"）
        scope: {
            value: '=',
            change: '&',
            blur: '&'
        },
        template: 		// 替换HTML (使用scope中的变量)
        '<input type="text" class="form-control BaseControl" style="ime-mode:disabled;text-align:right;" oncontextmenu="return false;" ' +
        'ng-model="DisplayValue" ng-show="Visible" ng-disabled="!Enabled" ng-keypress="keypress()" ng-focus="focus()" ng-blur="textBlur()"/>',
        replace: true,			// 使用模板替换原始标记
        transclude: true,		// 不复制原始HTML内容
        controller: ['$scope', function($scope) {
            $scope.DisplayValue = '';

            //可以输入的字符
            var keyCodes = [45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
            $scope.keypress = function() {
                var selectText = BaseFunction.getSelectText(event.srcElement);
                var laveText = event.srcElement.value.substr(0, selectText.Start) +
                    event.srcElement.value.substr(selectText.End, event.srcElement.value.length);

                if(event.keyCode == 45){    // "-"
                    if(this.MinValue != undefined && parseFloat(this.MinValue) >= 0){
                        window.event.returnValue = false;
                    }

                    if (selectText.Start != 0 || laveText.indexOf("-") >= 0) {
                        window.event.returnValue = false;
                    }
                }
                else if(event.keyCode == 46){   // "."
                    if(selectText.Start == 0){  //第一个位置不允许输入"."
                        window.event.returnValue = false;
                    }
                    else if($scope.Round != null && $scope.Round.Precision == 0){
                        window.event.returnValue = false;
                    }
                    else if(selectText.Start == 1){     //如果是负数，第二个位置不允许输入"."
                        if(laveText.indexOf("-") >= 0){
                            window.event.returnValue = false;
                        }
                    }

                    if (laveText.indexOf(".") >= 0) {  //如果剩下的文本还包含"."，则不能输入
                        window.event.returnValue = false;
                    }
                }
                else if(keyCodes.indexOf(event.keyCode) < 0){
                    event.returnValue = false;
                }
            };

            $scope.focus = function() {
                isBlur = false;
                $scope.DisplayValue = $scope.value;
                event.srcElement.select();
            };

            $scope.textChange = function(){
                if($scope.DisplayValue != undefined && $scope.DisplayValue != null && $scope.DisplayValue.toString().trim() != '') {
                    $scope.DisplayValue = Number($scope.DisplayValue);

                    if ($scope.MinValue != undefined) {
                        if ($scope.DisplayValue < $scope.MinValue) {
                            $scope.DisplayValue = $scope.MinValue;
                        }
                    }

                    if ($scope.MaxValue != undefined) {
                        if ($scope.DisplayValue > $scope.MaxValue) {
                            $scope.DisplayValue = $scope.MaxValue;
                        }
                    }

                    if ($scope.Round != null) {
                        $scope.value = Number($scope.Round.formatNumber($scope.DisplayValue));
                        $scope.DisplayValue = $scope.value;
                    }
                    else{
                        $scope.value = $scope.DisplayValue;
                    }
                }
                else{
                    if($scope.IsEmpty){
                        $scope.value = null;
                        $scope.DisplayValue = '';
                    }
                    else{
                        $scope.value = 0;
                        $scope.DisplayValue = 0;
                    }
                }

                $scope.$digest();
                $scope.$parent.$digest();
                $scope.change();
            };

            var isBlur = false;
            $scope.textBlur = function(){
                isBlur = true;
                if($scope.Round != null){
                    $scope.DisplayValue = $scope.Round.formatPercent($scope.value);
                }
                $scope.blur();
            };

            $scope.$watch(
                function(){
                    return $scope.value;
                },
                function(){
                    if(isBlur){
                        isBlur = false;
                    }
                    else{
                        if ($scope.Round != null) {
                            $scope.DisplayValue = $scope.Round.formatPercent($scope.value);
                        }
                        else{
                            $scope.DisplayValue = ($scope.value * 100).toString() + "%";
                        }
                    }
                }
            );
        }],
        link: function (scope, element, attrs) {
            scope.Enabled = true;
            scope.Visible = true;
            scope.IsEmpty = true;
            scope.Round = null;
            scope.MinValue = null;
            scope.MaxValue = null;

            if (attrs["isempty"] != undefined && attrs["isempty"].toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["round"] != undefined && attrs["round"].trim() != "") {
                scope.Round = eval("(" + attrs["round"].trim() + ")");
            }
            if (attrs["minvalue"] != undefined && attrs["minvalue"].trim() != "") {
                scope.MinValue = parseFloat(attrs["minvalue"].trim());
            }
            if (attrs["maxvalue"] != undefined && attrs["maxvalue"].trim() != "") {
                scope.MaxValue = parseFloat(attrs["maxvalue"].trim());
            }
            if(scope.MinValue != null && scope.MaxValue != null){
                if(scope.MinValue > scope.MaxValue){
                    BaseFunction.alert("最小值不能大于最大值", '程序参数设置错误');
                    return;
                }
            }

            if(scope.Round != null){
                if(scope.Round.Precision == undefined) {
                    BaseFunction.alert("舍入必须设置精度", '程序参数设置错误');
                }
                var precision = scope.Round.Precision;
                var roundType = BaseEnum.RoundType.AccondValueRound;
                var roundValue = 5;

                if(scope.Round.RoundType != undefined){
                    roundType = scope.Round.RoundType;
                }
                if(scope.Round.RoundValue != undefined){
                    roundValue = scope.Round.RoundValue;
                }

                scope.Round = new BaseClass.Round(precision, roundType, roundValue);
            }

            element[0].addEventListener('change', function(){scope.textChange()}, false);

            scope.$watch(
                function(){
                    return scope.value;
                },
                function(){
                    if(scope.Round != null){
                        if(scope.value != undefined && scope.value != null) {
                            scope.DisplayValue = scope.Round.formatNumber(scope.value);
                        }
                        else{
                            scope.DisplayValue = '';
                        }
                    }
                    else{
                        if(scope.value != undefined && scope.value != null) {
                            scope.DisplayValue = (scope.value * 100).toString() + "%";;
                        }
                        else{
                            scope.DisplayValue = '';
                        }
                    }
                }
            );

            scope.$watch(
                function(){
                    return attrs["enabled"];
                },
                function(){
                    if (attrs["enabled"] != undefined && attrs["enabled"].trim().toLocaleLowerCase() == "false") {
                        scope.Enabled = false;
                    }
                    else{
                        scope.Enabled = true;
                    }
                }
            );

            scope.$watch(
                function(){
                    return attrs["visible"]
                },
                function(){
                        if (attrs["visible"] != undefined && attrs["visible"].trim().toLocaleLowerCase() == "false") {
                            scope.Visible = false;
                        }
                        else{
                            scope.Visible = true;
                        }
                }
            );
        }
    }
}]);
